package com.homelink.crashhandle.service;

import android.net.NetworkInfo;
import android.telephony.TelephonyManager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;

public class NetworkChangeReceiver extends BroadcastReceiver
{
	public static final int NETWORK_TYPE_UNKNOWN = 0;
	public static final int NETWORK_TYPE_WIFI = 1;
	public static final int NETWORK_TYPE_MOBILE = 2;

	@Override
	public void onReceive(Context context, Intent intent)
	{
		if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction()))
		{
			if (isConnectNet(context))
			{
				Intent myIntent = new Intent(context, UploadFileService.class);
				context.startService(myIntent);
			}
			else
			{
			}
		}
	}

	public static boolean isConnectNet(Context context)
	{
		ConnectivityManager conManager = (ConnectivityManager) context
		        .getSystemService(Context.CONNECTIVITY_SERVICE);
		if (conManager == null)
		{
			return false;
		}
		else
		{
			NetworkInfo[] info = conManager.getAllNetworkInfo();
			if (info != null)
			{
				for (int i = 0; i < info.length; i++)
				{
					if (info[i].isConnected())
					{
						return true;
					}
				}
			}
		}
		return false;
	}

	public static int getNetType(Context context)
	{
		int netType = NETWORK_TYPE_UNKNOWN;
		ConnectivityManager connMgr = (ConnectivityManager) context
		        .getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
		if (networkInfo != null)
		{
			if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI)
			{
				netType = NETWORK_TYPE_WIFI;
			}
			else
			{
				TelephonyManager telmng = (TelephonyManager) context
				        .getSystemService(Context.TELEPHONY_SERVICE);
				if (telmng.getDataState() == TelephonyManager.DATA_CONNECTED)
				{
					netType = NETWORK_TYPE_MOBILE;
				}
			}
		}

		return netType;
	}

}
